package com.chijun.mform;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.alibaba.fastjson.JSON;
import com.chijun.mform.create.ICreateFormListener;
import com.chijun.mform.create.IServerSaveOverResult;
import com.chijun.mform.create.IWaitResult;
import com.chijun.mform.create.activity.FormSelectCreateTypeActivity;
import com.chijun.mform.create.dialog.IGetServerPersonResult;
import com.chijun.mform.create.field.Field;
import com.chijun.mform.create.mode.Form;
import com.chijun.mform.create.mode.FormAdmin;
import com.chijun.mform.create.mode.FormApprovePerson;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormFieldOption;
import com.chijun.mform.create.mode.FormFilled;
import com.chijun.mform.create.mode.FormGroup;
import com.chijun.mform.create.mode.FormIcon;
import com.chijun.mform.create.mode.FormOptionReField;
import com.chijun.mform.create.mode.FormProcessToFieldPermission;
import com.chijun.mform.create.mode.FormSaveData;
import com.chijun.mform.create.mode.FormUser;
import com.chijun.mform.full.mode.ModeFormFile;
import com.chijun.mform.full.ActivityFormFullIn;
import com.chijun.mform.full.mode.ModeFormOrdinaryFieldData;
import com.chijun.mform.full.IHandleWriterData;
import com.chijun.mform.full.mode.ModeFullForm;
import com.chijun.mform.process.IHandlerLoadFormFull;
import com.chijun.mform.process.LoadFullFormDataActivity;
import com.chijun.mform.test.CreateFormServiceImpl;
import com.example.ccj.b.c.custom.tree.TreeMode;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.JsonUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ThreadUtils;
import com.example.ccj.u.ThreadUtilsListener;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.server.MyObserver;
import com.example.ccj.u.server.Result;
import com.example.ccj.u.sqlite.SqliteExcuteCommand;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;

public class FormBuilder implements ICreateFormListener{
    public static final String TABLE_FORM_NAME = "form";
    public static final String TABLE_FORM_GROUP_NAME = "form_group";
    public static final String TABLE_FORM_ICON_NAME = "form_icon";
    public static final String TABLE_FORM_FIELD_NAME = "form_field";
    public static final String TABLE_FORM_FIELD_OPTION_NAME = "form_field_option";
    public static final String TABLE_FORM_FIELD_OPTION_RE_FIELD_NAME = "form_field_option_re_field";
    public static final String TABLE_FORM_APPROVE_PROCESS_NAME = "form_approve_process";
    public static final String TABLE_FORM_APPROVE_PROCESS_PERSON_NAME = "form_approve_process_person";
    public static final String TABLE_FORM_APPROVE_PROCESS_TO_FIELD_PERMISSION_NAME = "form_approve_process_to_field_permission";
    public static final String TABLE_FORM_USER = "form_user";
    public static final String TABLE_FORM_FILLED = "form_filled";
    public static final String TABLE_FORM_ADMIN = "form_admin";
    public static final String TABLE_NAME_LAUNCHED = "form_launched";
    public static final String TABLE_NAME_IMAGE = "form_image";
    public static final String TABLE_NAME_OrdinaryFieldData = "form_ordinary_field_data";


    public static String BUCKET_NAME = "chijun-1320231608"; //腾讯cos文件存储桶
    public static String DI_YU = "ap-beijing"; //腾讯cos存储桶地域
    public static int RONG_QI = 2; //2腾讯cos存储  1:阿里OSS
    public static String  LOGIN_USER_ID_KEY = "user_id";     //当前登录人员的key保存在SP中
    //组织名称
    public static String organization_name = "山东省驰珺网络科技有限公司";//文件前缀
    public static List<Integer> CannotSetPermissionsFieldTypeArray;     //不可设置审批权限的字段类型数组
    public static int THE_NUMBER_OF_FORMS_THAT_ARE_FETCHED_AT_A_TIME = 10;  //拉取表单已填写数量时每次获取的最大数量; 默认10


    /**
     * 创建sql表
     * @param context 上下文
     */
    public static void createSqlForm(Context context){

//        deleteTable(context);//删除表

        // TODO: 2024/12/23 这是 新建表单的数据
        //创建表单表
        SqliteExcuteCommand.createTable(context, Form.class);
        //表单类型表
        SqliteExcuteCommand.createTable(context, FormGroup.class);
        //表单图标表
        SqliteExcuteCommand.createTable(context, FormIcon.class);

        //字段表
        SqliteExcuteCommand.createTable(context, FormField.class);
        //字段选项表
        SqliteExcuteCommand.createTable(context, FormFieldOption.class);
        //字段选项关联字段表
        SqliteExcuteCommand.createTable(context, FormOptionReField.class);

        //流程表
        SqliteExcuteCommand.createTable(context, FormApproveProcess.class);
        //流程审批人员表
        SqliteExcuteCommand.createTable(context, FormApprovePerson.class);
        //流程审批人节点对表单内字段的权限
        SqliteExcuteCommand.createTable(context, FormProcessToFieldPermission.class);
        //表单可见部门
        SqliteExcuteCommand.createTable(context, FormFilled.class);
        //表单可见人员
        SqliteExcuteCommand.createTable(context, FormUser.class);
        //表单管理员
        SqliteExcuteCommand.createTable(context, FormAdmin.class);

        SqliteExcuteCommand.createTable(context, ModeFullForm.class);
        SqliteExcuteCommand.createTable(context, ModeFormFile.class);
        SqliteExcuteCommand.createTable(context, ModeFormOrdinaryFieldData.class);

    }
    public static void deleteTable(Context context){
        SqliteExcuteCommand.deleteTable(context, Form.class);
        SqliteExcuteCommand.deleteTable(context, FormGroup.class);
        SqliteExcuteCommand.deleteTable(context, FormIcon.class);
        SqliteExcuteCommand.deleteTable(context, FormField.class);
        SqliteExcuteCommand.deleteTable(context, FormFieldOption.class);
        SqliteExcuteCommand.deleteTable(context, FormOptionReField.class);
        SqliteExcuteCommand.deleteTable(context, FormApproveProcess.class);
        SqliteExcuteCommand.deleteTable(context, FormApprovePerson.class);
        SqliteExcuteCommand.deleteTable(context, FormProcessToFieldPermission.class);
        SqliteExcuteCommand.deleteTable(context, FormFilled.class);
        SqliteExcuteCommand.deleteTable(context, FormUser.class);
        SqliteExcuteCommand.deleteTable(context, FormAdmin.class);
        SqliteExcuteCommand.deleteTable(context, ModeFullForm.class);
        SqliteExcuteCommand.deleteTable(context, ModeFormFile.class);
        SqliteExcuteCommand.deleteTable(context, ModeFormOrdinaryFieldData.class);
    }

    public static void clearTableData(Context context){
        SqliteExcuteCommand.clearTable(context, Form.class);
        SqliteExcuteCommand.clearTable(context, FormGroup.class);
        SqliteExcuteCommand.clearTable(context, FormIcon.class);
        SqliteExcuteCommand.clearTable(context, FormField.class);
        SqliteExcuteCommand.clearTable(context, FormFieldOption.class);
        SqliteExcuteCommand.clearTable(context, FormOptionReField.class);
        SqliteExcuteCommand.clearTable(context, FormApproveProcess.class);
        SqliteExcuteCommand.clearTable(context, FormApprovePerson.class);
        SqliteExcuteCommand.clearTable(context, FormProcessToFieldPermission.class);
        SqliteExcuteCommand.clearTable(context, FormFilled.class);
        SqliteExcuteCommand.clearTable(context, FormUser.class);
        SqliteExcuteCommand.clearTable(context, FormAdmin.class);
        SqliteExcuteCommand.clearTable(context, ModeFullForm.class);
        SqliteExcuteCommand.clearTable(context, ModeFormFile.class);
        SqliteExcuteCommand.clearTable(context, ModeFormOrdinaryFieldData.class);
    }

    private static void print(String name, List<?> objects){
        if (objects == null) {
            LogUtils.e("<"+name + ">没有数据");
            return;
        }
        StringBuilder builder = new StringBuilder();
        for (Object object : objects) {
            builder.append("<").append(name).append("> ").append(JSON.toJSONString(object)).append("\n");
        }
        LogUtils.d(builder);
    }

    //字段类型列表
    private Field[] fields;
    //表单类型列表
    private List<FormGroup> formGroupList;
    //表单图标
    private List<FormIcon> formIconList;
    //日期格式类型文本
    private List<String> timeType;

    private List<TreeMode> treeModeList;
    private Map<String,TreeMode> treeModeMap;


    private static FormBuilder formBuilder;
    public static FormBuilder getInstance(){
        if (formBuilder == null) {
            synchronized (FormBuilder.class){
                formBuilder = new FormBuilder();
                createSqlForm(ActivityUtils.getTopActivity());
                return formBuilder;
            }
        }
        return formBuilder;
    }

    /**
     * 显示创建新表单activity
     * @param context 上下文
     */
    public void showCreateFormActivity(Context context){
        Intent intent = new Intent(context, FormSelectCreateTypeActivity.class);
        context.startActivity(intent);
    }

    /**
     * 打开填写表单activity
     * @param context 上下文
     * @param formId 表单的id
     */
    public void showLoadFormActivityToFormId(Context context, String formId){
        Intent intent = new Intent(context, ActivityFormFullIn.class);
        intent.putExtra("form_id",formId);
        context.startActivity(intent);
    }


    /**
     * 加载表单所填写的数据
     * @param context 上下文
     * @param formFullId 填写的表单数据编号
     */
    public void showLoadFormFullActivityToFormFullId(Context context, String formFullId){
        Intent intent = new Intent(context, LoadFullFormDataActivity.class);
        intent.putExtra("form_full_id",formFullId);
        ((Activity)context).startActivity(intent);
    }


    public Field[] getFields() {
        if (fields == null) {
            fields = new Field[18];

            Field  f1 = new Field(1,"单行输入框","","请输入");
            Field  f2 = new Field(2,"多行输入框","","请输入");
            Field  f3 = new Field(3,"单选项","","请选择");
            Field  f4 = new Field(4,"多选项","","请选择");
            Field  f5 = new Field(5,"数字输入","","请输入");
            Field  f6 = new Field(6,"日期","","请选择");
            Field  f7 = new Field(7,"日期区间","","请选择");
            Field  f8 = new Field(8,"说明文字","","请输入");
            Field  f9 = new Field(9,"身份证","","请输入");
            Field  f10 = new Field(10,"图片","","请选择");
            Field  f11 = new Field(11,"金额","","请输入");
            Field  f12 = new Field(12,"附件","","请选择");
            Field  f13 = new Field(13,"经纬度","","请选择");
            Field  f14 = new Field(14,"计算公式","","请输入");
            Field  f15 = new Field(15,"联系人","","手写");
            Field  f16 = new Field(16,"手写","","请选择");
            Field  f17 = new Field(17,"关联其他表单","","请扫描");
            Field  f18 = new Field(18,"扫码","","请扫描");



            fields[0] = f1;
            fields[1] = f2;
            fields[2] = f3;
            fields[3] = f4;
            fields[4] = f5;
            fields[5] = f6;
            fields[6] = f7;
            fields[7] = f8;
            fields[8] = f9;
            fields[9] = f10;
            fields[10] = f11;
            fields[11] = f12;
            fields[12] = f13;
            fields[13] = f14;
            fields[14] = f15;
            fields[15] = f16;
            fields[16] = f17;
            fields[17] = f18;
        }

        return fields;
    }
    public List<FormGroup> getFormGroupList() {
        return formGroupList;
    }
    public List<FormIcon> getFormIconList() {
        return formIconList;
    }
    public List<String> getTimeType() {
        return timeType;
    }

    public void setFields(Field[] fields) {
        this.fields = fields;
    }

    public void setFormGroupList(List<FormGroup> formGroupList) {
        this.formGroupList = formGroupList;
    }

    public void setFormIconList(List<FormIcon> formIconList) {
        this.formIconList = formIconList;
    }

    public void setTimeType(List<String> timeType) {
        this.timeType = timeType;
    }

    public List<TreeMode> getTreeModeList() {
        return treeModeList;
    }



    public void setTreeModeList(List<TreeMode> treeModeList) {
        this.treeModeList = treeModeList;

        ThreadUtils.executeByIo(new ThreadUtilsListener<Object>() {
            @Override
            public Object doInBackground() {
                treeModeMap = new HashMap<>();
                for (TreeMode treeMode : treeModeList) {
                    treeModeMap.put(treeMode.dataId,treeMode);
                }
                return null;
            }
        });
    }

    public Map<String, TreeMode> getTreeModeMap() {
        return treeModeMap;
    }

    public void setTreeModeMap(Map<String, TreeMode> treeModeMap) {
        this.treeModeMap = treeModeMap;
    }


    /**
     * 获取新建表单的配置数据
     * @param iWaitResult 获取到配置的回调
     */
    @Override
    public void getCreateFormConfig(IWaitResult iWaitResult) {
        CreateFormServiceImpl.getInstance().getCreateFormData()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Result>() {
                    @Override
                    public void onNext(Result result) {
                        iWaitResult.onResult(result.getData());
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        iWaitResult.onError(e.getMessage());
                    }
                });
    }

    /**
     * 获取人员列表
     * @param iGetServerPersonResult 人员列表回调
     * @return 从服务器返回数据直接返回null即可
     */
    @Override
    public List<TreeMode> resultTreeModeList(IGetServerPersonResult iGetServerPersonResult) {
        CreateFormServiceImpl.getInstance().getCreateProcessPerson().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Result>() {
                    @Override
                    public void onNext(Result result) {
                        if (!StringUtils.isEmpty(result.getData())) {
                            List<TreeMode> treeModeList = JsonUtils.toListBean(result.getData(), TreeMode.class);
                            LogUtils.d("解析后的人员配置：" + treeModeList.size());
                            if (treeModeList.isEmpty()) {
                                ToastUtils.showShort("人员列表解析失败：" + result.getData());
                            } else {
                                iGetServerPersonResult.result(treeModeList);
                                FormBuilder.getInstance().setTreeModeList(treeModeList);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtils.showShort("获取人员列表失败：" + e.getMessage());
                    }
                });
        return null;
    }
}
